<!-- 编辑支付模版 -->
<!-- 编辑支付模版 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    alignCenter
    width="85vw"
    :title="isEdit ? '编辑支付模版' : '新增支付模版'"
    draggable
    appendToBody
    destroyOnClose
    lockScroll
    :closeOnClickModal="false"
    @opened="handleOpened"
  >
    <el-form ref="elFormRef" :model="formData" :rules="rules" scrollToError :validateOnRuleChange="false">
      <div style="display: flex; flex-direction: row; width: 100%; padding: 15px">
        <div v-auto-animate style="flex: 1">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="formData.templateName" :maxlength="36" clearable placeholder="请输入模板名称"></el-input>
          </el-form-item>
          <el-form-item label="默认选中" prop="selectIndex">
            <el-select v-model="formData.selectIndex" placeholder="请选择默认选中" clearable>
              <el-option v-for="(_item, index) in formData.productList" :key="index" :label="`第 ${index + 1} 项`" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <!--
            <el-form-item label="模板类型" prop="templateType">
            <box-from-border>
            <el-radio-group v-model="formData.templateType">
            <el-radio label="K币充值模板 (个人中心)" :value="1"></el-radio>
            <el-radio label="会员充值模板 (个人中心)" :value="2"></el-radio>
            <el-radio label="播放解锁模板 (短剧播放页)" :value="4"></el-radio>
            </el-radio-group>
            </box-from-border>
            </el-form-item>
          -->
          <el-form-item v-if="formData.templateType === 4" label="广告解锁" prop="advertUnlock">
            <box-from-border>
              <el-radio-group v-model="formData.advertUnlock">
                <el-radio label="关闭" :value="0"></el-radio>
                <el-radio label="开启" :value="1"></el-radio>
              </el-radio-group>
            </box-from-border>
          </el-form-item>
        </div>
        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; margin-left: 20px">
          <page-simulation-template :selectIndex="formData.selectIndex" :templateProductList="formData.productList"></page-simulation-template>
          <span style="margin-top: 10px">示例</span>
        </div>
      </div>
      <el-form-item label="模板配置" prop="productList" labelPosition="top">
        <div style="position: absolute; top: -36px; right: 0">
          <el-button size="small" type="primary" :disabled="formData.productList.length >= 6" :icon="IconPlus" @click="addItemClick">添加充值商品</el-button>
        </div>
        <el-table
          class="custom-table draggable-table"
          border
          height="48vh"
          :data="formData.productList"
          showOverflowTooltip
          stripe
          style="width: 100%"
          @row-click="rowClickHandler"
        >
          <template #empty>
            <base-empty description="暂无数据或加载失败"></base-empty>
          </template>
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="充值类型" prop="productType" minWidth="140">
            <template #default="{ row }">
              <el-select
                v-if="currentEditProp.prop === 'productType' && currentEditProp.id === row.uuid"
                :ref="
                  (e) => {
                    editInputRefs(e, `productType${row.uuid}`);
                  }
                "
                v-model="row.productType"
                placeholder="充值类型"
                clearable
                @blur="editInputBlurHandler(null, true)"
                @change="editInputChangeHandler(`productType${row.uuid}`)"
              >
                <el-option v-for="item in productTypeList" :key="item.value" :disabled="item.disabled" :label="item.label" :value="item.value"></el-option>
              </el-select>
              <div v-else class="table-cell-custom">
                {{ productTypeList.find((foo) => foo.value === row.productType)?.label || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="productPrice" minWidth="170">
            <template #default="{ row }">
              <base-input-number
                v-if="currentEditProp.prop === 'productPrice' && currentEditProp.id === row.uuid"
                :ref="
                  (e) => {
                    editInputRefs(e, `productPrice${row.uuid}`);
                  }
                "
                v-model="row.productPrice"
                :decimals="2"
                verify="add_float"
                placeholder="金额"
                clearable
                @blur="editInputBlurHandler"
                @change="productPriceChangeHandler(row)"
              >
                <template #append>元</template>
              </base-input-number>
              <div v-else class="table-cell-custom">{{ row.productPrice || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="K币/天数" prop="productQuantity" minWidth="180">
            <template #default="{ row }">
              <base-input-number
                v-if="currentEditProp.prop === 'productQuantity' && currentEditProp.id === row.uuid"
                :ref="
                  (e) => {
                    editInputRefs(e, `productQuantity${row.uuid}`);
                  }
                "
                v-model="row.productQuantity"
                :max="row.productType !== 1 ? 90 : Infinity"
                :decimals="2"
                verify="add_int"
                placeholder="请输入"
                clearable
                @blur="editInputBlurHandler"
                @change="productQuantityChangeHandler(row)"
              >
                <template #append>{{ row.productType === 1 ? '个' : '天' }}</template>
              </base-input-number>
              <div v-else :class="{ 'table-cell-custom': row.productType !== 4 }">
                {{ row.productType === 4 ? '剧目买断' : row.productQuantity || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="赠送K币" prop="giveCoins" minWidth="140">
            <template #default="{ row }">
              <span>{{ row.giveCoins || '-' }}</span>
              <!--              <base-input-number -->
              <!--                v-if="currentEditProp.prop === 'giveCoins' && currentEditProp.id === row.uuid" -->
              <!--                :ref=" -->
              <!--                  (e) => { -->
              <!--                    editInputRefs(e, `giveCoins${row.uuid}`); -->
              <!--                  } -->
              <!--                " -->
              <!--                v-model="row.giveCoins" -->
              <!--                :decimals="2" -->
              <!--                verify="add_int" -->
              <!--                placeholder="请输入" -->
              <!--                clearable -->
              <!--                @blur="editInputBlurHandler" -->
              <!--              > -->
              <!--                <template #append>个</template> -->
              <!--              </base-input-number> -->
              <!--              <div v-else :class="{ 'table-cell-custom': row.productType !== 4 }">{{ row.giveCoins || '-' }}</div> -->
            </template>
          </el-table-column>
          <el-table-column label="商品名" prop="productName" minWidth="180">
            <template #default="{ row }">
              <el-input
                v-if="currentEditProp.prop === 'productName' && currentEditProp.id === row.uuid"
                :ref="
                  (e) => {
                    editInputRefs(e, `productName${row.uuid}`);
                  }
                "
                v-model="row.productName"
                maxlength="100"
                placeholder="商品名"
                clearable
                @blur="editInputBlurHandler"
              ></el-input>
              <div v-else class="table-cell-custom">{{ row.productName || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="营销文案" prop="marketingDesc" minWidth="180">
            <template #default="{ row }">
              <el-input
                v-if="currentEditProp.prop === 'marketingDesc' && currentEditProp.id === row.uuid"
                :ref="
                  (e) => {
                    editInputRefs(e, `marketingDesc${row.uuid}`);
                  }
                "
                v-model="row.marketingDesc"
                maxlength="100"
                placeholder="营销文案"
                clearable
                @blur="editInputBlurHandler"
              ></el-input>
              <div v-else class="table-cell-custom">{{ row.marketingDesc || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="角标" prop="recommendTags" minWidth="120">
            <template #default="{ row }">
              <el-input
                v-if="currentEditProp.prop === 'recommendTags' && currentEditProp.id === row.uuid"
                :ref="
                  (e) => {
                    editInputRefs(e, `recommendTags${row.uuid}`);
                  }
                "
                v-model="row.recommendTags"
                maxlength="100"
                placeholder="营销文案"
                clearable
                @blur="editInputBlurHandler"
              ></el-input>
              <div v-else class="table-cell-custom">{{ row.recommendTags || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="是否展示" prop="showStatus" minWidth="90">
            <template #default="{ row }">
              <div>
                <el-switch
                  v-model="row.showStatus"
                  style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
                  inlinePrompt
                  activeText="是"
                  inactiveText="否"
                  :activeValue="1"
                  :inactiveValue="0"
                ></el-switch>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100" align="center" headerAlign="center">
            <template #default="{ row }">
              <el-button circle class="handle" size="small" title="排序" :icon="IconSolarSortVerticalLineDuotone" style="cursor: grabbing"></el-button>
              <el-button circle type="danger" size="small" title="删除" :icon="IconDelete" @click="handleDel(row.uuid)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item labelWidth="0em">
        <div style="width: 100%; padding-top: 20px">
          <el-button style="width: 100%" type="success" :loading="loaging" :disabled="loaging" @click="onSubmit">
            <span>保存</span>
            <span class="hide" style="margin-left: 4px; font-size: 12px">(拖动表格内的拖拽按钮可排序)</span>
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
  import IconPlus from '~icons/ep/plus';
  import IconSolarSortVerticalLineDuotone from '~icons/solar/sort-vertical-line-duotone';
  import IconDelete from '~icons/ep/delete';
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import Sortable from 'sortablejs';
  import { ElInput, ElSelect, type FormInstance, type FormRules } from 'element-plus';
  import type { MarketingProduct, TemplateProductMarketingInfo } from '@/api/marketing-management';
  import { generateUuid } from '@/utils/common';

  type $ShowData = {
    type: 'add' | 'edit';
    /** 模板信息 */
    referralTemplate?: TemplateProductMarketingInfo;
    /** 保存 */
    submit: (res: TemplateProductMarketingInfo) => Promise<boolean>;
  };

  let submit: $ShowData['submit'] = () => Promise.resolve(true);
  const action = ref<'add' | 'edit'>('add');
  const loaging = ref(false);
  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);

  const formData = reactive<TemplateProductMarketingInfo>({
    advertUnlock: 1,
    productTemplateId: undefined,
    templateName: '',
    templateType: 4,
    selectIndex: 0,
    productList: [],
  });

  const rules = computed<FormRules<TemplateProductMarketingInfo>>(() => {
    const len = formData.productList.length;
    const _rules: FormRules<TemplateProductMarketingInfo> = {
      templateName: [
        { required: true, type: 'string', message: '请输入模板名称', trigger: ['blur', 'change'] },
        { required: true, min: 1, max: 48, type: 'string', message: '模板名称不合法', trigger: ['blur', 'change'] },
      ],
      templateType: [
        { required: true, type: 'number', message: '请选择模板类型', trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [1, 2, 4], message: '模板类型不合法', trigger: ['blur', 'change'] },
      ],
      advertUnlock: [
        { required: true, type: 'number', message: '请选择是否开启广告解锁', trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [0, 1], message: '广告解锁不合法', trigger: ['blur', 'change'] },
      ],
      selectIndex: [
        { required: true, type: 'number', message: '请选择默认选中', trigger: ['blur', 'change'] },
        { type: 'number', min: 0, max: len, message: `择默认选中不合法`, trigger: ['blur', 'change'] },
      ],
      productList: [
        { required: true, type: 'array', message: '请添加充值商品', trigger: ['blur', 'change'] },
        { type: 'array', min: 2, max: 6, message: `充值商品只能选 2 到 6 个`, trigger: ['blur', 'change'] },
      ],
    };
    return _rules;
  });

  /** 新增一项 */
  function addItemClick() {
    if (formData.productList.length < 6) {
      formData.productList.push({
        uuid: generateUuid(),
        giveCoins: '',
        marketingDesc: '',
        productName: '',
        productPrice: '',
        productQuantity: '',
        productTemplateId: '',
        productType: 1,
        recommendTags: '',
        showStatus: 1,
      });
    }
  }

  /** 删除 */
  function handleDel(uuid: string) {
    // const index = formData.productList.findIndex((item) => item.productId === productId);
    // index >= 0 && formData.productList.splice(index, 1);
    formData.productList = formData.productList.filter((v) => v.uuid !== uuid);
  }

  /**
   * 提交
   */
  async function onSubmit() {
    try {
      formData.advertUnlock = formData.templateType === 4 ? formData.advertUnlock : 0;
      await elFormRef.value?.validate();
      for (let i = 0, len = formData.productList.length; i < len; i++) {
        const foo = formData.productList[i]!;
        if (!foo.productType) {
          ElToast.warning(`模板配置中请选择序号为${i + 1}的充值类型`);
          return;
        }
        if (!foo.productPrice) {
          ElToast.warning(`模板配置中请选择序号为${i + 1}的金额`);
          return;
        }
        if (foo.productType !== 4 && !foo.productQuantity) {
          ElToast.warning(`模板配置中请选择序号为${i + 1}的${foo!.productType === 1 ? '获币' : '天数'}`);
          return;
        }
        if (foo.productType === 1 && Number(foo.productQuantity) > Math.round(Number(foo.productPrice) * 300)) {
          ElToast.warning(`模板配置中序号为${i + 1}的金额与K币最大比例为1:300`);
          return;
        }
        if (!foo.marketingDesc) {
          ElToast.warning(`模板配置中请选择序号为${i + 1}的营销文案`);
          return;
        }
        if (!foo.productName) {
          ElToast.warning(`模板配置中请选择序号为${i + 1}的商品名`);
          return;
        }
      }
      try {
        loaging.value = true;
        await submit(formData!);
        loaging.value = false;
        hide();
      } catch (error) {
        loaging.value = false;
      }
    } catch (error) {
      ElToast.error('保存失败，请完善表单，-BD002');
    }
  }

  /**
   * 显示
   */
  function show(data: $ShowData) {
    action.value = data.type;
    submit = 'submit' in data && typeof data.submit === 'function' ? data.submit : () => Promise.resolve(true);
    formData.templateName = data.referralTemplate ? data.referralTemplate.templateName : '';
    formData.templateType = data.referralTemplate ? data.referralTemplate.templateType : 4;
    formData.selectIndex = data.referralTemplate ? data.referralTemplate.selectIndex : 0;
    if (data.referralTemplate && Array.isArray(data.referralTemplate?.productList)) {
      formData.productList = data.referralTemplate.productList.map((v) => {
        v.uuid = generateUuid();
        return v;
      });
    } else {
      formData.productList = [];
    }
    formData.productTemplateId = data.referralTemplate ? data.referralTemplate.productTemplateId : undefined;
    formData.advertUnlock = data.referralTemplate ? data.referralTemplate.advertUnlock : 0;

    dialogVisible.value = true;
  }

  const isEdit = computed(() => action.value === 'edit');

  const currentEditProp = reactive({
    prop: '',
    id: '',
  });

  const editInputRef = ref<Record<string, InstanceType<typeof ElInput> | InstanceType<typeof ElSelect>> | null>({});
  const editInputRefs = (el: any, key: string) => {
    if (el && editInputRef.value) {
      editInputRef.value[key] = el;
    }
  };
  let blurInputTimeout = null as NodeJS.Timeout | null;
  const allowEditProp = ['productType', 'productPrice', 'productQuantity', 'giveCoins', 'marketingDesc', 'productName', 'recommendTags'];
  const rowClickHandler = (row: MarketingProduct, col: any) => {
    if (!col) {
      return;
    }
    if (col.property === 'productQuantity' && row.productType === 4) {
      return;
    }
    if (col && allowEditProp.includes(col.property)) {
      if (blurInputTimeout) {
        clearTimeout(blurInputTimeout);
        blurInputTimeout = null;
      }
      currentEditProp.prop = col.property;
      currentEditProp.id = row.uuid;

      setTimeout(() => {
        if (editInputRef.value) {
          const key = `${col.property}${row.uuid}`;
          console.log(key,"key")
          const instance = editInputRef.value[key] as InstanceType<typeof ElSelect>;

          console.log(instance,"instance")

          instance.focus();

          if (instance?.toggleMenu) {
            instance.toggleMenu();
          }
        }
      });
    }
  };

  const editInputChangeHandler = (key: string) => {
    if (editInputRef.value) {
      const instance = editInputRef.value[key] as InstanceType<typeof ElSelect>;
      instance.blur();
    }
  };

  const editInputBlurHandler = (_: any, sel = false) => {
    if (sel) {
      blurInputTimeout = setTimeout(() => {
        currentEditProp.prop = '';
        currentEditProp.id = '';
      }, 300);
    } else {
      currentEditProp.prop = '';
      currentEditProp.id = '';
    }
  };

  const productPriceChangeHandler = (row: MarketingProduct) => {
    if (row.productType === 1 && row.productPrice) {
      row.productQuantity = `${Math.round(Number(row.productPrice) * 100)}`;
      row.giveCoins = `0`;
    }
  };

  const productQuantityChangeHandler = (row: MarketingProduct) => {
    //    row.productQuantity
    //  row.productType === 1 ? '个' : '天'
    if (row.productType === 1 && row.productQuantity && row.productPrice) {
      // if (Number(row.productPrice) * 100 >= Number(row.productQuantity)) {
      //   row.giveCoins = `0`;
      // } else {
      //   const val = Number(row.productQuantity) - Number(row.productPrice) * 100;
      //   row.giveCoins = `${val}`;
      // }
      const val = Number(row.productQuantity) - Number(row.productPrice) * 100;
      if (val > 0) {
        row.giveCoins = `${Math.round(val)}`;
      } else {
        row.giveCoins = `0`;
      }
    }
  };

  onBeforeUnmount(() => {
    editInputRef.value = null;
  });

  /** 打开动画完成时 */
  function handleOpened() {
    nextTick(() => {
      const tbody: HTMLElement | null = document.querySelector('.draggable-table .el-table__body-wrapper tbody');
      tbody &&
        new Sortable(tbody, {
          handle: '.handle', // handle's class
          animation: 150,
          // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
          onEnd: ({ newIndex, oldIndex }) => {
            if (typeof newIndex === 'number' && typeof oldIndex === 'number') {
              const list: MarketingProduct[] = JSON.parse(JSON.stringify(formData.productList));
              const currentRow = list.splice(oldIndex, 1)[0]!;
              list.splice(newIndex, 0, currentRow);
              formData.productList = [];
              nextTick(() => {
                formData.productList = list;
              });
            }
          },
        });
    });
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  defineExpose({ show, hide });

  const productTypeList = computed(() => {
    return [
      { label: '充值K币', value: 1, disabled: false },
      { label: '充值会员', value: 2, disabled: false },
      { label: '解锁短剧', value: 4, disabled: formData.productList.some((v) => v.productType === 4) },
    ];
  });

  // watch(
  //     () => formData.productList,
  //     (e) => {
  //       //解决存量问题
  //       e.forEach(item=>{
  //         if(item.productType !==1 && item.productQuantity){
  //           let val = Number(item.productQuantity);
  //
  //           if(val > 90){
  //             val = 90
  //             item.productQuantity = ''
  //             setTimeout(()=>{
  //               item.productQuantity = val.toString();
  //             },20)
  //           }else{
  //             item.productQuantity = val.toString();
  //           }
  //
  //         }
  //       })
  //     },
  //     {deep: true}
  // );
</script>

<style lang="scss" scoped>
  :deep(.custom-table) .el-table__body .cell .table-cell-custom {
    display: flex;
    align-items: center;
    width: 100%;
    min-height: 32px;
    padding: 0 10px;
    cursor: pointer;
    border: 1px var(--el-color-primary) solid;
    border-radius: 3px;
  }
</style>
